import numpy as np
import re
import json

from resolver.instance import KeyPointsIns

'''
    func get_pic_key_points 处理单个txt文件，将其结构化
    @params
    text_file_path:txt数据所在路径名称
    text_name:txt文件名（不含拓展名）
    is_full_path:指示传入的text_file_path是否为文件的全路径
'''
def get_pic_key_points(text_file_path, text_name, is_full_path):
    if is_full_path:
        full_text_path = text_file_path
    else:
        full_text_path = '{}/{}.txt'.format(text_file_path, text_name)
    # 加载文本文件到内存
    f = open(full_text_path)
    raw_text = f.read()
    bbox_pattern = "({'bbox': array\()(.*?)(dtype=float32)"
    bbox_find_list = re.findall(bbox_pattern, raw_text, re.DOTALL)
    res = []
    for i in range(0, len(bbox_find_list)):
        key_points_ins = KeyPointsIns(name=text_name, obj_id=i)
        key_points_ins.set_bbox(bbox_find_list_resolver(bbox_find_list[i]))
        res.append(key_points_ins)

    key_points_pattern = "('keypoints': array\(\[)(.*?)(\], dtype=float32\)\})"
    key_points_find_list = re.findall(key_points_pattern, raw_text, re.DOTALL)
    if len(key_points_find_list) != len(bbox_find_list):
        print("文件解析失败！bbox关键点与keyPoints不匹配")
        return
    else:
        for i in range(0, len(key_points_find_list)):
            res[i].set_key_points(key_points_list_resolver(key_points_find_list[i]))
    # print(json.dumps(res, default=lambda o: o.__dict__, sort_keys=True, indent=4))
    return res


def bbox_find_list_resolver(bbox_raw_text):
    bbox_raw_list = bbox_raw_text[1].replace(" ", "").replace("\n", "")[1:-2].split(",")
    return [float(x) for x in bbox_raw_list]


def key_points_list_resolver(key_points_raw_text):
    key_points_raw_list = key_points_raw_text[1] \
        .replace(" ", "") \
        .replace("\n", "") \
        .replace("[", "") \
        .replace("]", "") \
        .split(",")
    res = []
    group = []
    for i in range(0, len(key_points_raw_list)):
        group.append(float(key_points_raw_list[i]))
        if (i + 1) % 3 == 0:
            res.append(group)
            group = []
    return res
